from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import User

# Create your views here.


# 登陆状态验证装饰器
def login_check(func):
    def inner(request, *args, **kwargs):
        login_status = request.session.get('login_status')  # 通过session获取登录状态
        if login_status == 1:
            ret = func(request, *args, **kwargs)  # 登录状态为1，表示登陆中，执行其他页面函数
            return ret
        else:
            return redirect('myapp:login')  # 否则返回登陆页面
    return inner


def login(request):
    if request.method == 'GET':
        return render(request, 'myapp/login.html')
    elif request.method == 'POST':
        # 获取登录的用户名密码
        uname = request.POST.get('uname')
        upwd = request.POST.get('upwd')
        # 对比数据库
        result = User.objects.filter(u_name=uname, u_password=upwd).count()
        if result:  # 用户名密码正确
            response = redirect('myapp:index')  # 跳转到首页
            request.session['u_name'] = uname  # 设置session值u_name用户名
            request.session['login_status'] = 1  # 设置登陆状态1表示登陆中
            request.session.set_expiry(None)  # 设置session的有效时间，使用默认两周
            request.session.clear_expired()  # 删除已将过期的session，当前时间之前的
            return response
        else:
            return HttpResponse('用户名密码错误！')


@login_check
def index(request):
    login_status = request.session.get('login_status')
    u_name = request.session.get('u_name')
    return render(request, 'myapp/index.html', locals())


@login_check
def home(request):
    login_status = request.session.get('login_status')
    u_name = request.session.get('u_name')
    return render(request, 'myapp/home.html', locals())


def logout(request):
    request.session.flush()
    ret = redirect('myapp:login')
    ret.delete_cookie('sessionid')
    return ret